package day10.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author oldliu
 * @since 1.0
 */
public class AdvanceFileServer {
    public static void main(String[] args) {
        ServerSocket st = null;
        try {
            st = new ServerSocket(9999);
            System.out.println("服务器启动成功，监听在9999端口");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        while (true) {
            try {
                final Socket s = st.accept();
                //new FileThread(s).start();
                new ObjectThread(s).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class FileThread extends Thread {
    private final Socket s;

    public FileThread(Socket s) {
        this.s = s;
    }

    public static final String fileName = "D:\\Documents\\图片和资料\\job-salary.png";

    @Override
    public void run() {
        System.out.println(s + "连接成功");
        try {
            InputStream in = s.getInputStream();//用不上

            OutputStream out = s.getOutputStream();
            //一步读取文件，发byte数组给客户端
            FileInputStream fin = new FileInputStream(fileName);
            byte[] b = new byte[fin.available()];
            int len = fin.read(b);
            fin.close();
            out.write(b, 0, len);
            out.flush();
            System.out.println("文件发送给" + s + "成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println(s + "退出了。。。");
                s.close();
            } catch (Exception e) {

            }
        }
    }
}

class ObjectThread extends Thread {
    private final Socket s;

    public ObjectThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println(s + "连接成功");
        Map<String, String> map = new HashMap<>();
        map.put("最高", "赵润泽");
        map.put("最帅", "孟东升");
        map.put("最矮", "老刘");
        map.put("当前时间", String.valueOf(new Date()));
        try {

            OutputStream out = s.getOutputStream();
            //一步读取文件，发byte数组给客户端
            ObjectOutputStream oout = new ObjectOutputStream(out);
            oout.writeObject(map);
            out.flush();
            System.out.println("文件发送给" + s + "成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println(s + "退出了。。。");
                s.close();
            } catch (Exception e) {

            }
        }
    }
}